package com.teaching.management.controller.api;

import com.teaching.management.entity.Teacher;
import com.teaching.management.entity.User;
import com.teaching.management.repository.TeacherRepository;
import com.teaching.management.repository.UserRepository;
import com.teaching.management.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpSession;
import jakarta.transaction.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/teacher/profile")
public class TeacherProfileRestController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/update")
    @Transactional
    public ResponseEntity<?> updateProfile(@RequestBody Teacher updatedTeacher, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return ResponseEntity.status(401).body("请先登录");
        }

        Teacher currentTeacher = teacherService.getTeacherByUserId(user.getUserId());
        if (currentTeacher == null) {
            return ResponseEntity.status(404).body("教师信息不存在");
        }

        // 更新基本信息
        currentTeacher.setName(updatedTeacher.getName());
        currentTeacher.setGender(updatedTeacher.getGender());
        currentTeacher.setEmail(updatedTeacher.getEmail());
        currentTeacher.setPhone(updatedTeacher.getPhone());
        currentTeacher.setOffice(updatedTeacher.getOffice());
        currentTeacher.setBio(updatedTeacher.getBio());

        Teacher savedTeacher = teacherRepository.save(currentTeacher);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "个人信息更新成功");
        response.put("teacher", savedTeacher);

        return ResponseEntity.ok(response);
    }

    @PostMapping("/password")
    @Transactional
    public ResponseEntity<?> changePassword(@RequestBody Map<String, String> passwordData, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return ResponseEntity.status(401).body("请先登录");
        }

        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");

        if (oldPassword == null || newPassword == null) {
            return ResponseEntity.badRequest().body("请提供原密码和新密码");
        }

        User currentUser = userRepository.findById(user.getUserId()).orElse(null);
        if (currentUser == null) {
            return ResponseEntity.status(404).body("用户不存在");
        }

        // 简单密码验证 - 假设存储的是明文密码
        // 注意：实际项目中应使用加密方式
        if (!oldPassword.equals(currentUser.getPassword())) {
            return ResponseEntity.badRequest().body("原密码不正确");
        }

        // 更新密码
        currentUser.setPassword(newPassword);
        userRepository.save(currentUser);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "密码修改成功");

        return ResponseEntity.ok(response);
    }

    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("avatar") MultipartFile file, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return ResponseEntity.status(401).body("请先登录");
        }

        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return ResponseEntity.status(404).body("教师信息不存在");
        }

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择一个文件");
        }

        try {
            // 创建上传目录
            String uploadDir = "uploads/avatars/teachers/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成文件名
            String filename = teacher.getTeacherId() + "_" + System.currentTimeMillis() + "_"
                    + StringUtils.cleanPath(file.getOriginalFilename());
            Path filePath = uploadPath.resolve(filename);

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 更新数据库中的头像路径
            String avatarUrl = "/" + uploadDir + filename;
            teacher.setAvatar(avatarUrl);
            teacherRepository.save(teacher);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "头像上传成功");
            response.put("avatarUrl", avatarUrl);

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }
}